<?php

namespace catchAdmin\storehouse\controller;

use catchAdmin\stock\model\WarehouseConfig;
use catchAdmin\storehouse\model\WarehousingSon;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\storehouse\model\Tray as TrayModel;
use think\Response;
use catcher\CatchAuth;
use think\facade\Db;

class Tray extends CatchController
{

    protected $trayModel;

    /**
     *
     * @time 2022/01/21 15:50
     * @param TrayModel $trayModel
     * @return mixed
     */
    public function __construct(TrayModel $trayModel)
    {
        $this->trayModel = $trayModel;
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->trayModel->getList($user['tenant_id']));
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function create(CatchAuth $auth, Request $request): Response
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        if (empty($params['tray_id'])) {
            $params['tray_id'] = date('YmdHis');
        }
        $params['type'] = 'add';
        $params = $this->tray_info($params);

        if ($params['code'] === 0) {
            return CatchResponse::fail($params['msg']);
        }
        Db::startTrans();
        try {
            $this->trayModel->storeBy($params['data']);
            $this->counts($params['data']['warehousing_son_id']);
            Db::commit();
            return CatchResponse::success('添加成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('添加失败');
        }
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function createAdd(CatchAuth $auth, Request $request): Response
    {
        $params = $request->post();
        $user = $auth->user();
        $data = [];
        $product = [];
        $warehousing_son = Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing']['warehousing_son_id'])->find();
        $commodity = Db::table('db_product')->where([
            'goods_id' => $params['goods_info']['goods_id'],
            'deleted_at' => 0
        ])->find();
        if (empty($commodity)) {
            return CatchResponse::fail('商品料号不存在！');
        }
        $box_number = 0;
        $configId = '20250708142453';
        Db::startTrans();
        try {
            Db::table('db_warehousing_sn')->where([
                'warehousing_id' => $params['warehousing']['warehousing_id'],
                'warehousing_son_id' => $params['warehousing']['warehousing_son_id'],
                'goods_id' => $commodity['goods_id']
            ])->delete();
            Db::table('db_tray')->where('warehousing_son_id',$params['warehousing']['warehousing_son_id'])->delete();
            foreach ($params['list'] as $k => $v) {
                //tray
                if (array_key_exists('tray_id', $v) && $v['tray_id']) {
//                    $where_tray_find = [];
//                    $where_tray_find[] = ['tray_id', '=', $v['tray_id']];
//                    $where_tray_find[] = ['tenant_id', '=', $user['tenant_id']];
//
////                    if (array_key_exists('id', $v) && !empty($v['id'])) {
////                        $where_tray_find[] = ['id', '<>', $v['id']];
////                    }
//                    $tray = (new TrayModel())
//                        ->where($where_tray_find)
//                        ->find();
//                    if ($tray) {
//                        Db::table('db_tray')->where('warehousing_son_id',$tray['warehousing_son_id'])->delete();
//                    }
                    $data[$k]['tray_id'] = $v['tray_id'];
                } else {
                    $user_co_code = Db::table('users')->where('id', $user['tenant_id'])->value('co_code');
                    $data[$k]['tray_id'] = $user_co_code . 'T' . date('YmdHis') . $k . rand(1000, 9999);
                }
                $data[$k]['warehousing_id'] = $params['warehousing']['warehousing_id'];
                $data[$k]['warehousing_son_id'] = $params['warehousing']['warehousing_son_id'];
                $data[$k]['config_id'] = $configId;
                $data[$k]['tenant_id'] = $user['tenant_id'];
                $data[$k]['status'] = '0';
                $data[$k]['LOT1'] = $v['LOT1'] ?? '';
                $data[$k]['LOT2'] = $v['LOT2'] ?? '';
                $data[$k]['LOT3'] = $v['LOT3'] ?? '';
                //呵呵了 12.21打个布丁
                if (!empty($v['goods_status'])) {
                    $data[$k]['goods_status'] = $v['goods_status'];
                } else {
                    if (empty($v['status'])) {
                        $data[$k]['goods_status'] = 'Good';
                    } else {
                        $data[$k]['goods_status'] = $v['status'];
                    }
                }
                $data[$k]['created_at'] = time();
                $data[$k]['box_number'] = $v['box_number'];
                $box_number += $v['box_number'];
                $data[$k]['number'] = $v['number'];
                $data[$k]['batch_number'] = $warehousing_son['batch_number'];
                $data[$k]['creator_id'] = $user['id'];
                //product
                $product[$k]['warehousing_id'] = $params['warehousing']['warehousing_id'];
                $product[$k]['warehousing_son_id'] = $warehousing_son['warehousing_son_id'];
                $product[$k]['goods_name'] = $warehousing_son['goods_name'];
                $product[$k]['goods_id'] = $commodity['goods_id'];
                $product[$k]['goods_Cname'] = $commodity['goods_Cname'];
                $product[$k]['goods_Ename'] = $commodity['goods_Ename'];
                $product[$k]['manufacturer_id'] = $commodity['manufacturer_id'];
                $product[$k]['manufacturer_name'] = Db::table('db_manufacturer')->where('manufacturer_id', $commodity['manufacturer_id'])->value('manufacturer_name');
                $product[$k]['supplier_id'] = $commodity['supplier_id'];
                $product[$k]['supplier_name'] = Db::table('db_supplier')->where('supplier_id', $commodity['supplier_id'])->value('supplier_name');
                $product[$k]['packing_id'] = $warehousing_son['packing_id'];
                $product[$k]['p_barcode'] = $warehousing_son['packing_id'];
                $packing = Db::table('db_packing')->where('packing_id', $warehousing_son['packing_id'])->find();
                $product[$k]['packing_num'] = $packing['packing_num'];
                $product[$k]['unit_name'] = $packing['unit_name'];
                $product[$k]['number'] = $v['number'];
                $product[$k]['box_number'] = $v['box_number'];
                $product[$k]['created_at'] = time();
                $product[$k]['tenant_id'] = $user['tenant_id'];
                $product[$k]['creator_id'] = $user['id'];
                $product[$k]['tray_id'] = $data[$k]['tray_id'];
                $product[$k]['specification'] = $packing['packing_num'] . ' / ' . $packing['unit_name'] . ' /' . $packing['layup_num'];
                $product[$k]['LOT1'] = $data[$k]['LOT1'];
                $product[$k]['LOT2'] = $data[$k]['LOT2'];
                $product[$k]['LOT3'] = $data[$k]['LOT3'];

                $snData = [];
                if (!empty($v['sn'])) {
                    // 替换中文逗号为英文逗号
                    $sn = $v['sn'];
                    $snArr = [];
                    $sn = preg_replace('/，/', ',', $sn);
                    $sn = preg_replace('/,/', ',', $sn);
                    $sn = str_replace("\n", ",", $sn);
                    $snArr[] = $sn;
                    if (strpos($sn, ',') !== false) {
                        $snArr = array_filter(explode(',', $sn));
                    }
                    $unSnArr = array_unique($snArr);
                    if (count($snArr) != count($unSnArr)) {
                        throw new \Exception('sn码不能重复！');
                    }

                    if (count($snArr) != intval($v['number'])) {
                        throw new \Exception('请填写与待入库数量相等的sn码！');
                    }

                    $palletNo = !empty($v['pallet_no']) ? $v['pallet_no'] : 'P' . date('YmdHis') . mt_rand(1000, 9999);
                    foreach ($snArr as $sVal) {
                            if(!empty(Db::table('db_warehousing_sn')->where([
                                'tenant_id' => $user['tenant_id'],
                                'sn' => $sVal,
                                'deleted_at'=>0,
                                'warehousing_id' => $params['warehousing']['warehousing_id'],
                                'warehousing_son_id' => $params['warehousing']['warehousing_son_id'],
                            ])->find())){
                                throw new \Exception('sn码：'.$sVal.',已存在！');
                            }
                            $snData[] = [
                                'warehousing_id' => $params['warehousing']['warehousing_id'],
                                'warehousing_son_id' => $params['warehousing']['warehousing_son_id'],
                                'config_id' => $configId,
                                'number' => 1,
                                'sn' => $sVal,
                                'creator_id' => $user['id'],
                                'created_at' => time(),
                                'pallet_no' => $palletNo,
                                'tray_id' => $data[$k]['tray_id'],
                                'tenant_id' => $user['tenant_id'],
                                'goods_id' => $commodity['goods_id'],
                            ];
                    }
                    if (!empty($snData)) {
                        Db::table('db_warehousing_sn')->insertAll($snData);
                    }
                } else {
                    throw new \Exception('请填写与待入库数量相等的sn码！');
                }
            }
            //【硬】删除之前系统默认分配的托盘表和入库托盘产品表
            Db::table('db_warehousing_product')->where('warehousing_son_id', $warehousing_son['warehousing_son_id'])->delete();

            //重新写入编辑后的数据
            Db::table('db_tray')->insertAll($data);
            Db::table('db_warehousing_product')->insertAll($product);
            $arr = ['tray_number' => count($data), 'box_number' => $box_number];
            Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing']['warehousing_son_id'])->update($arr);
            Db::commit();
            return CatchResponse::success('添加成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }
    }

//    //手工分配 添加推盘、箱、片
//    public function handworkCreateAdd(CatchAuth $auth,Request $request)
//    {
//        $params = $request->post();
//        $user = $auth->user();
//        $data = [];$product=[];
//        $warehousing_son=Db::table('db_warehousing_son')->where('warehousing_son_id',$params['warehousing']['warehousing_son_id'])->find();
//        $commodity=Db::table('db_product')->where('goods_name',$warehousing_son['goods_name'])->find();
//        if(empty($commodity)){
//            Db::rollback();
//            return CatchResponse::fail('商品料号不存在！');
//        }
//        $box_number=0;
//        foreach ($params['list'] as $k=>$v){
//            //tray
//            if( array_key_exists('tray_id',$v) &&  $v['tray_id']){
//                $where_tray_find = [];
//                $where_tray_find[] = ['tray_id','=',$v['tray_id']];
//                $where_tray_find[] = ['tenant_id','=',$user['tenant_id']];
//
//                if(array_key_exists('id',$v) && !empty($v['id'])){
//                    $where_tray_find[] =  ['id','<>',$v['id']];
//                }
//                $tray=(new \catchAdmin\storehouse\model\Tray())
//                    ->where($where_tray_find)
//                    ->find();
//                if($tray){
//                    return CatchResponse::fail('托盘码'.$v['tray_id'].'已存在！');
//                }
//
//                $data[$k]['tray_id']=$v['tray_id'];
//
//            }else{
//                //$data[$k]['tray_id']='t'.date('YmdHis').$k.rand(100,999) . $user->tenant_id;
//                $user_co_code = Db::table('users')->where('id',$user['tenant_id'])->value('co_code');
//                $data[$k]['tray_id']= $user_co_code .  'T' .date('YmdHis').$k.rand(1000,9999);
//            }
//            $data[$k]['warehousing_id']=$params['warehousing']['warehousing_id'];
//            $data[$k]['warehousing_son_id']=$params['warehousing']['warehousing_son_id'];
//            $data[$k]['config_id']=$v['config_id'];
//            $data[$k]['tenant_id']=$user['tenant_id'];
//            $data[$k]['status']='0';
//
//            $data[$k]['LOT1']= $v['LOT1'] ?? '';
//            $data[$k]['LOT2']= $v['LOT2'] ?? '';
//            $data[$k]['LOT3']= $v['LOT3'] ?? '';
//
//            //呵呵了 12.21打个布丁
//            if(!empty($v['goods_status'])){
//                $data[$k]['goods_status']=$v['goods_status'];
//            }else{
//                if(empty($v['status'])){
//                    $data[$k]['goods_status']='Good';
//                }else{
//                    $data[$k]['goods_status']=$v['status'];
//                }
//            }
//
//            $data[$k]['created_at']=time();
//            $data[$k]['box_number']=$v['box_number'];
//            $box_number+=$v['box_number'];
//            $data[$k]['number']=$v['number'];
//            $data[$k]['batch_number']=$warehousing_son['batch_number'];
//            $data[$k]['creator_id']=$user['id'];
//            //product
//            $product[$k]['warehousing_id']=$params['warehousing']['warehousing_id'];
//            $product[$k]['warehousing_son_id']=$warehousing_son['warehousing_son_id'];
//            $product[$k]['goods_name']=$warehousing_son['goods_name'];
//            $product[$k]['goods_id']=$commodity['goods_id'];
//            $product[$k]['goods_Cname']=$commodity['goods_Cname'];
//            $product[$k]['goods_Ename']=$commodity['goods_Ename'];
//            $product[$k]['manufacturer_id']=$commodity['manufacturer_id'];
//            $product[$k]['manufacturer_name']=Db::table('db_manufacturer')->where('manufacturer_id',$commodity['manufacturer_id'])->value('manufacturer_name');
//            $product[$k]['supplier_id']=$commodity['supplier_id'];
//            $product[$k]['supplier_name']=Db::table('db_supplier')->where('supplier_id',$commodity['supplier_id'])->value('supplier_name');
//            $product[$k]['packing_id']=$warehousing_son['packing_id'];
//            $product[$k]['p_barcode']=$warehousing_son['packing_id'];
//            $packing=Db::table('db_packing')->where('packing_id',$warehousing_son['packing_id'])->find();
//            $product[$k]['packing_num']=$packing['packing_num'];
//            $product[$k]['unit_name']=$packing['unit_name'];
//            $product[$k]['number']=$v['number'];
//            $product[$k]['box_number']=$v['box_number'];
//            $product[$k]['created_at']=time();
//            $product[$k]['tenant_id']=$user['tenant_id'];
//            $product[$k]['creator_id']=$user['id'];
//            $product[$k]['tray_id']=$data[$k]['tray_id'];
//            $product[$k]['specification']=$packing['packing_num'].' / '.$packing['unit_name'] . ' /' .  $packing['layup_num'];
//
//            $product[$k]['LOT1'] = $data[$k]['LOT1'];
//            $product[$k]['LOT2'] = $data[$k]['LOT2'];
//            $product[$k]['LOT3'] = $data[$k]['LOT3'];
//        }
//        Db::startTrans();
//        try {
//            //【硬】删除之前系统默认分配的托盘表和入库托盘产品表
//            Db::table('db_tray')->where('warehousing_son_id',$warehousing_son['warehousing_son_id'])->delete();
//            Db::table('db_warehousing_product')->where('warehousing_son_id',$warehousing_son['warehousing_son_id'])->delete();
//
//            //重新写入编辑后的数据
//            Db::table('db_tray')->insertAll($data);
//            Db::table('db_warehousing_product')->insertAll($product);
//            $arr=['tray_number'=>count($data),'box_number'=>$box_number];
//            Db::table('db_warehousing_son')->where('warehousing_son_id',$params['warehousing']['warehousing_son_id'])->update($arr);
//            Db::commit();
//            return CatchResponse::success('添加成功');
//        } catch (\Exception $exception) {
//            Db::rollback();
//            return CatchResponse::fail('添加失败');
//        }
//    }
//

    /**
     * @param $id
     * @return Response
     */
    public function read($id): Response
    {
        return CatchResponse::success($this->trayModel->findBy($id));
    }

    /**
     *
     * @time 2022/01/21 15:50
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        $params = $request->filterEmptyField()->post();
        $params['type'] = 'edit';
        $params = $this->tray_info($params);
        if ($params['code'] === 0) {
            return CatchResponse::fail($params['msg']);
        }
        Db::startTrans();
        try {
            $this->trayModel->updateBy($params['data']['id'], $params['data']);
            $this->counts($params['data']['warehousing_son_id']);
            Db::commit();
            return CatchResponse::success('修改成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('修改失败');
        }
    }

    /**
     *
     * @time 2022/01/21 15:50
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $id = $request->post('id');
        $tray_info = Db::table('db_tray')->where('id', $id)->find();
        $son_info = Db::table('db_warehousing_son')->where('warehousing_son_id', $tray_info['warehousing_son_id'])->find();
        $data = [];
        $data['box_number'] = $son_info['box_number'] - $tray_info['box_number'];
        $data['tray_number'] = $son_info['tray_number'] - 1;
        Db::startTrans();
        try {
            Db::table('db_warehousing_son')->where('warehousing_son_id', $tray_info['warehousing_son_id'])->update($data);
            Db::table('db_tray')->where('id', $id)->delete();
            Db::table('db_warehousing_sn')->where([
                'warehousing_son_id' => $tray_info['warehousing_son_id'],
                'tray_id' => $tray_info['tray_id']
            ])->delete();
            Db::commit();
            return CatchResponse::success('删除成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('删除成功');
        }
    }

    /**
     * 统计托盘数和入库箱数
     * @return string
     */
    public function counts($warehousing_son_id)
    {
        $where = [];
        $where[] = ['warehousing_son_id', '=', $warehousing_son_id];
        $where[] = ['deleted_at', '=', 0];
        $count = DB::name('db_tray')->field('count(id) as number,SUM(box_number) as box_number')->where($where)->find();

        $count['box_number'] = $count['box_number'] ? $count['box_number'] : 0;

        $info = DB::name('db_warehousing_son')
            ->where($where)
            ->update([
                'tray_number' => $count['number'],
                'box_number' => $count['box_number'],
                'updated_at' => time()
            ]);
        return $info;
    }

    /**
     * 数据整理
     * @return array
     */
    public function tray_info($params)
    {
        //托盘和入库数量对比
        $numberson = Db::name('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->value('number');
        $where = [];
        if ($params['type'] === 'edit') {
            $where[] = ['id', '<>', $params['id']];
        }
        $where[] = ['warehousing_son_id', '=', $params['warehousing_son_id']];
        $where[] = ['deleted_at', '=', 0];

        $number = Db::name('db_tray')->field('SUM(number) as number')->where($where)->find();

        $number1 = intval($number['number']) + intval($params['number']);

        if ($number1 > $numberson) {
            return array('code' => 0, 'msg' => '入库数量大于商品剩余入库数，请核对入库数量');
        }
        if (!empty($params['config_ids'])) {
            $params['config_id'] = $params['config_ids'];
        }
        unset($params['config_ids']);
        unset($params['type']);
        return array('code' => 1, 'data' => $params);
    }

    /**
     * 剩余商品入库数量和包装数量
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function surplus(Request $request): Response
    {
        $warehousing_son_id = $request->post('warehousing_son_id');

        if (empty($warehousing_son_id)) {
            return CatchResponse::fail('缺少必要参数');
        }
        $where = [];
        $where[] = ['deleted_at', '=', 0];
        $where[] = ['warehousing_son_id', '=', $warehousing_son_id];
        $son = DB::name('db_warehousing_son')->where($where)
            ->field('number,packing_num,pallet_no')->find();

        $tray = Db::name('db_tray')->field('SUM(number) as number')->where($where)->find();

        $data['number'] = intval($son['number']) - intval($tray['number']);
        $data['packing_num'] = $son['packing_num'];
        $data['total_number'] = intval($son['number']);
        $data['pallet_no'] = $son['pallet_no'];

        return CatchResponse::success($data);
    }

    //一开始的分配计算
//    public function conversionList(CatchAuth $auth,Request $request)
//    {
//        $warehousing_son_id = $request->post('warehousing_son_id');
//
//        if (empty($warehousing_son_id)) {
//            return CatchResponse::fail('缺少必要参数warehousing_son_id');
//        }
//
//        $user = $auth->user();
//        return CatchResponse::success($this->trayModel->getAttrList($user['tenant_id']));
//    }

    public function conversionList(CatchAuth $auth, Request $request)
    {
        $warehousing_son_id = $request->post('warehousing_son_id');

        if (empty($warehousing_son_id)) {
            return CatchResponse::fail('缺少必要参数warehousing_son_id');
        }

        $user = $auth->user();
//        if(empty(Db::table('db_warehousing_son')->where('tenant_id',$user->tenant_id)->where('warehousing_son_id',$warehousing_son_id)->find())){
//            return CatchResponse::fail('订单不存在');
//        }

        //判断是否有订单，如果有订单返回数据库的

        $result = (new WarehousingSon)->autoConversionByWsonID($warehousing_son_id);

        return CatchResponse::success($result);
    }
}